package com.faithbj.controller.infoInput;

import com.faithbj.common.configuration.Pager;
import com.faithbj.common.model.CheckTotal;
import com.faithbj.common.model.Dictionary;
import com.faithbj.common.model.Region;
import com.faithbj.common.model.fm.FamilyMember;
import com.faithbj.common.service.RegionService;
import com.faithbj.common.utils.DictionaryUtil;
import com.faithbj.common.web.controller.BaseController;
import com.faithbj.process.ProcessApplicationService;
import com.faithbj.process.State;
import com.faithbj.process.TaskModel;
import com.faithbj.process.stats.VerifyReason;
import com.faithbj.service.CheckTotalService;
import com.faithbj.service.FamilyMemberService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * 信息核实
 * @author yfxue
 *
 */
@Controller
@RequestMapping("/infoverify")
public class InfoVerifyController extends BaseController {

	private static final long serialVersionUID = 922077900361587618L;

	private final Logger logger = LoggerFactory.getLogger(getClass());

	@Resource
	private CheckTotalService checkTotalService;
    @Resource
    private ProcessApplicationService processApplicationService;	
	@Resource
	private RegionService regionService;
	@Resource
	private DictionaryUtil dictionaryUtil;
	@Resource
	private FamilyMemberService familyMemberService;
    
    
	/**
	 * 信息核实待办列表,会从小熊哪里发一个
	 * @param pager
	 * @param map
	 * @return
	 */
	@RequestMapping(value = "/index")
	public String list(Pager pager,ModelMap map) {
		List<TaskModel> tasks = processApplicationService
				.listAvailableTasksWithContentByUserAndState(State.VERIFICATION,
						pager.getFirstResult(), pager.getPageSize());
		pager.setResult(tasks);
		pager.setTotalCount(processApplicationService.countAvailableTasksByUserAndState(State.VERIFICATION));
		map.put("pager", pager);
		return "/infoverify/index";		
	}	
	
	
	@RequestMapping(value = "/{id}/{taskId}/{result}")
	public String getCheckTotalById(@PathVariable("id") String id,@PathVariable("taskId") Long taskId,@PathVariable("result") Boolean result, ModelMap map) {

		CheckTotal checkTotal = checkTotalService.getCheckTotalById(id);
		Set<FamilyMember> members = checkTotal.getFamilyMembers();
		for (FamilyMember fm : members) {
			if (fm.getMainApplicant()) {
				map.put("fm", fm);
			}
		}
		List<Dictionary> types = dictionaryUtil.getListByTypeName("业务类型");
		List<Dictionary> idTypes = dictionaryUtil.getListByTypeName("证件类型");
		List<Dictionary> nations = dictionaryUtil.getListByTypeName("民族");
		List<Dictionary> politicalStatusList = dictionaryUtil
				.getListByTypeName("政治面貌");
		List<Dictionary> education = dictionaryUtil.getListByTypeName("文化程度");
		List<Dictionary> laborlost = dictionaryUtil.getListByTypeName("丧劳情况");
		List<Dictionary> maritalStatusList = dictionaryUtil
				.getListByTypeName("婚姻状况");
		List<Dictionary> householdTypeList = dictionaryUtil
				.getListByTypeName("户籍类型");
		List<Dictionary> disabilityDegreeList = dictionaryUtil
				.getListByTypeName("残疾等级");
		List<Dictionary> relaitionList = dictionaryUtil
				.getListByTypeName("与申请人代表关系");

		List<Region> citys = regionService.getRegionListByType(Region.COUNTRY);
		List<Region> streets = regionService.getRegionListByType(Region.STREET);

		map.put("educations", education);
		map.put("laborlost", laborlost);
		map.put("maritalStatusList", maritalStatusList);
		map.put("politicalStatusList", politicalStatusList);
		map.put("nations", nations);
		map.put("citys", citys);
		map.put("streets", streets);
		map.put("types", types);
		map.put("idTypes", idTypes);
		map.put("householdTypes", householdTypeList);
		map.put("disabilityDegreeList", disabilityDegreeList);
		map.put("relaitionList", relaitionList);

		map.put("taskId", taskId);// taskid，还要再传回去!要命啊！
		map.put("result", result.toString());// result，还要再传回去!要命啊！

		map.put("checkTotal", checkTotal);
		return "/infoverify/familyBasic";
	}
	
	@RequestMapping(value = "/familyMemberInfo/{id}/{taskId}/{result}")
	public String getFamilyMembers(@PathVariable String id,
			@PathVariable("taskId") Long taskId,
			@PathVariable("result") Boolean result, ModelMap map) {
		map.put("taskId", taskId);
		map.put("result", result.toString());

		List<FamilyMember> familyMembers = familyMemberService
				.getFamilyMembersByCheckTotal(id);
		map.put("familyMembers", familyMembers);

		List<Dictionary> types = dictionaryUtil.getListByTypeName("业务类型");
		List<Dictionary> idTypes = dictionaryUtil.getListByTypeName("证件类型");
		List<Dictionary> nations = dictionaryUtil.getListByTypeName("民族");
		List<Dictionary> politicalStatusList = dictionaryUtil
				.getListByTypeName("政治面貌");
		List<Dictionary> education = dictionaryUtil.getListByTypeName("文化程度");
		List<Dictionary> laborlost = dictionaryUtil.getListByTypeName("丧劳情况");
		List<Dictionary> maritalStatusList = dictionaryUtil
				.getListByTypeName("婚姻状况");
		List<Dictionary> householdTypeList = dictionaryUtil
				.getListByTypeName("户籍类型");
		List<Dictionary> disabilityDegreeList = dictionaryUtil
				.getListByTypeName("残疾等级");
		List<Dictionary> relaitionList = dictionaryUtil
				.getListByTypeName("与申请人代表关系");
		List<Dictionary> enclosures = dictionaryUtil
				.getListByTypeName("基本证明材料");

		List<Region> citys = regionService.getRegionListByType(Region.COUNTRY);
		List<Region> streets = regionService.getRegionListByType(Region.STREET);

		map.put("educations", education);
		map.put("laborlost", laborlost);
		map.put("maritalStatusList", maritalStatusList);
		map.put("politicalStatusList", politicalStatusList);
		map.put("nations", nations);
		map.put("citys", citys);
		map.put("streets", streets);
		map.put("types", types);
		map.put("idTypes", idTypes);
		map.put("householdTypes", householdTypeList);
		map.put("disabilityDegreeList", disabilityDegreeList);
		map.put("relaitionList", relaitionList);

		map.put("checkTotalId", id);
		map.put("enclosures", enclosures);

		// 获取家庭主申请人的证明材料列表
		for (FamilyMember fms : familyMembers) {
			if (fms.getMainApplicant())
				map.put("enclosurelist", fms.getEnclosures());
			map.put("mainfm", fms);
		}

		return "/infoverify/familyMember";
	}	

	
	@RequestMapping(value = "/familyMemberIncome/{id}/{taskId}/{result}")
	public String getFamilyMemberIncomes(@PathVariable String id,
			@PathVariable("taskId") Long taskId,
			@PathVariable("result") Boolean result, ModelMap map) {
		map.put("taskId", taskId);
		map.put("result", result.toString());

		List<FamilyMember> familyMembers = familyMemberService
				.getFamilyMembersByCheckTotal(id);
		CheckTotal ct = checkTotalService.getCheckTotalById(id);
		map.put("familyMembers", familyMembers);
		map.put("checkTotal", ct);
		return "/infoverify/memberIncome";
	}
	
	@RequestMapping(value = "/familyMemberProperty/{id}/{taskId}/{result}")
	public String getFamilyMemberProperties(@PathVariable("id") String id,
			@PathVariable("taskId") Long taskId,
			@PathVariable("result") Boolean result, ModelMap map) {
		map.put("taskId", taskId);
		map.put("result", result.toString());// taskid，还要再传回去!要命啊！

		List<FamilyMember> familyMembers = familyMemberService
				.getFamilyMembersByCheckTotal(id);
		map.put("familyMembers", familyMembers);
		map.put("checkTotalId", id);
		return "/infoverify/memberProperty";
	}	
	
	/**
	 * 显示发送核实意见页面
	 * 
	 * @param id
	 * @param map
	 * @return
	 */
	@RequestMapping(value = "/sendCheck/{id}/{taskId}/{result}")
	public String getFamilyMembersForSendCheck(@PathVariable String id,
			@PathVariable("taskId") Long taskId,@PathVariable("result") Boolean result, ModelMap map) {
		List<FamilyMember> familyMembers = familyMemberService
				.getFamilyMembersByCheckTotal(id);

		// 获取主申请人信息
		FamilyMember mainApply = null;
		for (FamilyMember fm : familyMembers) {
			if (fm.getMainApplicant())
				mainApply = fm;
		}
		// 获取登录用户实际姓名
		String username = getLoginUser().getName();

		// CheckTotal checkTotal = checkTotalService.getCheckTotalById(id);
		map.put("familyMembers", familyMembers);
		map.put("mainApply", mainApply);
		map.put("username", username);

		map.put("checkTotalId", id);
		map.put("taskId", taskId);
		map.put("result", result.toString());
		return "/infoverify/checkInfo";
	}

	/**
	 * 核实意见
	 */
	
	@RequestMapping(value = "/sendCheck", method = RequestMethod.POST)
    @ResponseBody
	public ModelMap sendCheck(VerifyReason verifyReason, String checkTotalId,	Long taskId) {
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("result", verifyReason.getName());
		CheckTotal checkTotal = checkTotalService.getCheckTotalById(checkTotalId);
		processApplicationService.completeTask(taskId, checkTotal, map);
        skipToComparison(taskId, checkTotal);
		ModelMap mMap=new ModelMap();
        mMap.put("status", "1");//跳转到基本信息页
		
		return mMap;
	}

    private void skipToComparison(long currentTaskId, CheckTotal checkTotal) {
        TaskModel task0 = processApplicationService.getTaskWithContent(currentTaskId);
        long processInstanceId = task0.getProcessInstanceId();
        skipTask(processInstanceId, State.EXPORT, checkTotal);
        skipTask(processInstanceId, State.IMPORT, checkTotal);
        skipTask(processInstanceId, State.SEND_AND_RECEIVE_FOR_COMPARISON, checkTotal);
    }

    private void skipTask(long processInstanceId, State state, CheckTotal checkTotal) {
        TaskModel task = null;
        boolean first = true;
        while (task == null) {
            if (!first) {
                try {
                    TimeUnit.MILLISECONDS.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            task = processApplicationService.getTaskByProcessInstanceIdAndState(processInstanceId, state);
            first = false;
        }
        processApplicationService.claimAndGroupStartTask(task.getId());
        processApplicationService.completeGroupTask(task.getId(), checkTotal);
    }
}
